// 封装请求
import { ElMessage } from 'element-plus'


export interface ResponseConfig {
  code: number,
  status: number,
  data: any,
  message: string
}
export interface ValueConfig {
  value: any,

}

let reqUrl: string

const fetch = (url: string, options?: any): Promise<any> => {
    const headers = { 
      "Content-Type": "application/json;charset=utf-8",
      'X-Requested-With': 'XMLHttpRequest',
      'Access-Control-Allow-Origin': '*'
    }
    const djangoUrl  = 'https://django.starbucket.xyz/'
    const apiUrl  = 'https://api.starbucket.xyz/'
    const localhost = 'https://127.0.0.1:8000/'
    // 因为有2个接口，做个接口判断
    if(url === 'information/' || url === 'productPrice1' || url === 'productPrice2' ){
      reqUrl = apiUrl + url
        return new Promise((resolve, reject) => {
          useFetch(reqUrl as string).then(({ data }: any) => {
            const value = data.value
              if (!data._rawValue) {
                  // 这里处理错误回调
                  reject(value)
              }   
              else {
                // 这里处理请求成功回调              
                resolve(ref(value))
              }
          }).catch((err: any) => {
              reject(err)
          })
      })
    }
    reqUrl = djangoUrl + url
    return new Promise((resolve, reject) => {
    //console.log(options);
      
        useFetch(reqUrl, { ...options, headers }).then(({ data }: any) => {
          const value = data.value
            if (!data._rawValue) {
              // 这里处理错误回调
              reject(value)
              ElMessage({
                message: data._rawValue.message,
                type: 'error',
                duration: 1000,
                center: true,
              })
            }   
             else {
              // 这里处理请求成功回调
              // ElMessage({
              //   message: data._rawValue.message,
              //   type: 'success',
              // })
              resolve(ref(value))
            }
        }).catch((err: any) => {
            reject(err)
        })
    })
}

export default new class Http {

    get(url: string, params?: any): Promise<any> {      
        return fetch(url, { method: 'GET', params })
    }

    post(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'POST', body })
    }

    put(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'PUT', body })
    }

    delete(url: string, body?: any): Promise<any> {
        return fetch(url, { method: 'DELETE', body })
    }
}
